package com.zudada.servermain.Service.ServiceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zudada.servermain.POJO.DTO.PortFacilityAddDTO;
import com.zudada.servermain.POJO.DTO.PortFacilityQueryDTO;
import com.zudada.servermain.POJO.DTO.PortFacilityUpdateDTO;
import com.zudada.servermain.POJO.VO.PortFacilityVO;
import com.zudada.servermain.POJO.entity.PortFacility;
import com.zudada.servermain.POJO.enums.ResultCode;
import com.zudada.servermain.Service.PortFacilityService;
import com.zudada.servermain.exception.ServiceException;
import com.zudada.servermain.mapper.PortFacilityMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PortFacilityServiceImpl extends ServiceImpl<PortFacilityMapper, PortFacility> implements PortFacilityService {

    @Autowired
    private PortFacilityMapper portFacilityMapper;

    @Override
    public boolean addPortFacility(PortFacilityAddDTO dto) {
        try {
            // 参数校验
            if (dto == null) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "港口设施信息不能为空");
            }
            if (dto.getPortId() == null || dto.getPortId().trim().isEmpty()) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "港口ID不能为空");
            }
            if (dto.getFacilityName() == null || dto.getFacilityName().trim().isEmpty()) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "设施名称不能为空");
            }

            PortFacility entity = new PortFacility();
            BeanUtils.copyProperties(dto, entity); // 复制属性
            entity.setUpdateTime(new Date()); // 设置更新时间

            // 如果没有指定 ID，可以由数据库自增或 UUID 生成
            // 假设 facilityID 是主键且手动传入
            // 若不传则可生成唯一 ID（如 UUID）
            if (entity.getFacilityId() == null || entity.getFacilityId().isEmpty()) {
                // 示例：生成 UUID
                entity.setFacilityId(java.util.UUID.randomUUID().toString());
            }

            int result = portFacilityMapper.insert(entity);
            if (result <= 0) {
                log.error("添加港口设施失败，插入结果：{}", result);
                throw new ServiceException(ResultCode.ERROR, "添加港口设施失败");
            }
            return true;
        } catch (ServiceException e) {
            throw e;
        } catch (DataAccessException e) {
            log.error("添加港口设施时发生数据库异常", e);
            throw new ServiceException(ResultCode.ERROR, "添加港口设施失败，数据库操作异常,(港口id可能不存在)");
        } catch (Exception e) {
            log.error("添加港口设施时发生未知异常", e);
            throw new ServiceException(ResultCode.ERROR, "添加港口设施失败，请稍后重试");
        }
    }

    /**
     * 根据港口设备id删除港口设施
     * @param facilityId 设施ID
     */
    @Override
    public void deleteById(String facilityId) {
        try {
            // 参数校验
            if (facilityId == null || facilityId.trim().isEmpty()) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "设施ID不能为空");
            }

            // 检查数据是否存在
            PortFacility existingFacility = portFacilityMapper.selectById(facilityId);
            if (existingFacility == null) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "港口设施不存在，无法删除");
            }

            // 调用MyBatis-Plus的删除方法（根据ID删除）
            int result = portFacilityMapper.deleteById(facilityId);
            if (result <= 0) {
                log.error("删除港口设施失败，删除结果：{}", result);
                throw new ServiceException(ResultCode.ERROR, "删除港口设施失败");
            }
        } catch (ServiceException e) {
            throw e;
        } catch (DataAccessException e) {
            log.error("删除港口设施时发生数据库异常，设施ID：{}", facilityId, e);
            throw new ServiceException(ResultCode.ERROR, "删除港口设施失败，数据库操作异常");
        } catch (Exception e) {
            log.error("删除港口设施时发生未知异常，设施ID：{}", facilityId, e);
            throw new ServiceException(ResultCode.ERROR, "删除港口设施失败，请稍后重试");
        }
    }

    /**
     * 修改港口设施接口
     * @param dto
     * @return
     */
    @Override
    public boolean updatePortFacility(PortFacilityUpdateDTO dto) {
        try {
            // 参数校验
            if (dto == null) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "港口设施信息不能为空");
            }
            if (dto.getFacilityId() == null || dto.getFacilityId().trim().isEmpty()) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "设施ID不能为空");
            }

            // 检查数据是否存在
            PortFacility existingFacility = portFacilityMapper.selectById(dto.getFacilityId());
            if (existingFacility == null) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "港口设施不存在，无法更新");
            }

            // 1. 构建查询条件：通过 facilityId 定位要修改的记录
            LambdaQueryWrapper<PortFacility> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(PortFacility::getFacilityId, dto.getFacilityId());

            // 2. 构建要更新的实体对象
            PortFacility entity = new PortFacility();
            entity.setPortId(dto.getPortId());
            entity.setFacilityName(dto.getFacilityName());
            entity.setFacilityType(dto.getFacilityType());
            entity.setCapacity(dto.getCapacity());
            entity.setEquipmentInfo(dto.getEquipmentInfo());
            entity.setStatus(dto.getStatus());
            Date updateTime = new Date();
            entity.setUpdateTime(updateTime);

            // 3. 执行更新操作
            int result = portFacilityMapper.update(entity, queryWrapper);
            if (result == 0) {
                log.error("更新港口设施失败，更新结果：{}，设施ID：{}", result, dto.getFacilityId());
                throw new ServiceException(ResultCode.ERROR, "更新港口设施失败");
            }
            return true;
        } catch (ServiceException e) {
            throw e;
        } catch (DataAccessException e) {
            log.error("更新港口设施时发生数据库异常，设施ID：{}", dto != null ? dto.getFacilityId() : "null", e);
            throw new ServiceException(ResultCode.ERROR, "更新港口设施失败，数据库操作异常");
        } catch (Exception e) {
            log.error("更新港口设施时发生未知异常，设施ID：{}", dto != null ? dto.getFacilityId() : "null", e);
            throw new ServiceException(ResultCode.ERROR, "更新港口设施失败，请稍后重试");
        }
    }

    /**
     * 港口设施查询
     * @param queryDTO
     * @return
     */
    @Override
    public List<PortFacilityVO> listPortFacilities(PortFacilityQueryDTO queryDTO) {
        try {
            // 参数校验
            if (queryDTO == null) {
                throw new ServiceException(ResultCode.PARAMS_ERROR, "查询参数不能为空");
            }

            // 构建查询条件
            LambdaQueryWrapper<PortFacility> queryWrapper = new LambdaQueryWrapper<>();
            if (queryDTO.getFacilityId() != null && !queryDTO.getFacilityId().trim().isEmpty()) {
                queryWrapper.eq(PortFacility::getFacilityId, queryDTO.getFacilityId());
            }
            if (queryDTO.getPortId() != null && !queryDTO.getPortId().trim().isEmpty()) {
                queryWrapper.eq(PortFacility::getPortId, queryDTO.getPortId());
            }
            if (queryDTO.getFacilityName() != null && !queryDTO.getFacilityName().trim().isEmpty()) {
                queryWrapper.like(PortFacility::getFacilityName, queryDTO.getFacilityName());
            }
            if (queryDTO.getFacilityType() != null && !queryDTO.getFacilityType().trim().isEmpty()) {
                queryWrapper.eq(PortFacility::getFacilityType, queryDTO.getFacilityType());
            }
            if (queryDTO.getStatus() != null && !queryDTO.getStatus().trim().isEmpty()) {
                queryWrapper.eq(PortFacility::getStatus, queryDTO.getStatus());
            }

            // 查询数据并转换为VO
            List<PortFacility> facilityList = list(queryWrapper);
            if (facilityList == null) {
                log.warn("查询港口设施列表返回null");
                return List.of();
            }
            return facilityList.stream().map(this::convertToVO).collect(Collectors.toList());
        } catch (ServiceException e) {
            throw e;
        } catch (DataAccessException e) {
            log.error("查询港口设施列表时发生数据库异常", e);
            throw new ServiceException(ResultCode.ERROR, "查询港口设施列表失败，数据库操作异常");
        } catch (Exception e) {
            log.error("查询港口设施列表时发生未知异常", e);
            throw new ServiceException(ResultCode.ERROR, "查询港口设施列表失败，请稍后重试");
        }
    }
    /**
     * Entity 转 VO
     */
    private PortFacilityVO convertToVO(PortFacility entity) {
        if (entity == null) {
            log.warn("转换VO时实体对象为null");
            return null;
        }
        try {
            PortFacilityVO vo = new PortFacilityVO();
            BeanUtils.copyProperties(entity, vo);
            return vo;
        } catch (Exception e) {
            log.error("转换PortFacility实体为VO时发生异常，设施ID：{}", entity.getFacilityId(), e);
            throw new ServiceException(ResultCode.ERROR, "数据转换失败");
        }
    }



}
